<template>
  <div class="paas-apply-template">
    <div class="paas-apply-item" v-for="(apply, index) in applyItems" :key="index">
      <div class="paas-apply-li">
        <div class="apply-name">
          <p class="name">{{$t('product.qrcodeSetting.paasApplyTemplate.paasName')}}</p>
          <span class="del" @click="onDel(index)"><i class="iconfont icon-delete"></i></span>
        </div>
        <el-input :placeholder="$t('product.qrcodeSetting.paasApplyTemplate.placeholder')" v-model="apply.applicationName"></el-input>
      </div>
      <div class="paas-apply-li">
        <div class="apply-name">
          <p class="name">{{$t('product.qrcodeSetting.paasApplyTemplate.linkPaasText')}}</p>
        </div>
        <el-cascader
          ref="cascader"
          v-model="apply.formTemplateValue" 
          :props="props"
          :options="formTemplateList"
          @change="(value)=>handleChange(value,index)"
        >
        </el-cascader>
        <el-input
          v-if="apply.templateBizId === 'CustomLink'"
          :placeholder="$t('common.base.tip.defaultPlaceholder')"
          :maxlength="FORM_FIELD_TEXT_MAX_LENGTH"
          v-model="apply.cusstomerLink"/>
      </div>
      <div class="paas-apply-li">
        <div class="apply-name">
          <p class="name">{{$t('product.qrcodeSetting.paasApplyTemplate.linkPaasIcon')}}</p>
        </div>
        <el-popover placement="right" :width="380" trigger="click">
          <div class="select-app-icon-logo">
            <div class="app-icon">
              <div v-for="item in iconColors" :key="item.color" class="logo-color"
                :style="{ background: `${item.color}` }" @click="selectColor(item.color, index)">
                <i v-if="item.color == apply.color" class="iconfont icon-duihao1" />
              </div>
            </div>
            <div class="app-logo">
              <div v-for="(item, idx) in iconList" :key="idx" class="app-logo-item"
                @click="selectAppIcon(item.className, index)">
                <div class="appIcon">
                  <i :class="['iconfont', item.className]"
                    :style="{ color: item.className == apply.icon ? apply.color : '' }" />
                </div>
              </div>
            </div>
            <div class="custom-image">
              <el-upload
                action="string"
                :before-upload="onBeforeUploadImage"
                :http-request="(val) => uploadImagePic(val, index)"
                accept=".jpg,.jpeg"
                :show-file-list="false"
                :disabled="loading"
              >
                <div>
                  <i class="iconfont icon-upload1"></i>
                  <span>{{ $t('product.qrcodeSetting.paasApplyTemplate.iconName') }}</span>
                </div>
              </el-upload>
              <span class="desc">{{ $t('product.qrcodeSetting.paasApplyTemplate.iconDesc') }}</span>
            </div>
          </div>
          <div class="apply-icon" slot="reference">
            <img v-if="apply.iconUrl" :src="apply.iconUrl" class="apply-icon-img" />
            <div v-else class="icon" :style="{ background: apply.color }">
              <i :class="['iconfont', apply.icon]"></i>
            </div>
            <span>{{$t('product.qrcodeSetting.paasApplyTemplate.clickText')}}</span>
          </div>
        </el-popover>
      </div>
    </div>
    <div class="add-apply" @click="addApply">
      <p>+ {{$t('product.qrcodeSetting.paasApplyTemplate.addText')}}</p>
    </div>
  </div>
</template>
<script>
/* api */
import * as PassApi from '@src/api/PassApi';
/* util */
import { iconColors, iconList, Default_Logo, Default_Color } from '../util/appIconList.ts';
import Uploader from 'packages/BaseUpload/uploader'
import { FORM_FIELD_TEXT_MAX_LENGTH } from '@src/model/const/Number.ts';
export default {
  name: 'paas-apply-template',
  props:{
    paasList: {
      type:Array,
      default:[]
    },
  },
  data() {
    return {
      props: {
        value: 'code',
        label: 'name',
        children: 'children',
      },
      iconColors,
      iconList,
      applyItems: [],
      formTemplateList: [],
      loading: false,
      FORM_FIELD_TEXT_MAX_LENGTH,
      needServerDeleFiles: [],
    };
  },
  mounted() {
    this.applyItems = this.paasList;
    this.fetchFormTemplateList();
  },
  methods: {
    /* 自定义图标*/
    onBeforeUploadImage(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error(this.$t('product.qrcodeSetting.paasApplyTemplate.imgValidType'));
      }
      if (!isLt2M) {
        this.$message.error(this.$t('product.qrcodeSetting.paasApplyTemplate.imgValidSiz'));
      }

      return isJPG && isLt2M;
    },
    uploadImagePic(param, index) {
      this.loading = true;
      Uploader.upload(param.file, '/files/upload')
          .then(result => {
            if (result.status != 0) {
              this.$message({
                message: `${result.message}`,
                duration: 1500,
                type: 'error',
              });
              return;
            }

            const {
              ossUrl = '',
              url = '',
              id = '',
            } = result.data;

            const iconUrl =  ossUrl ?? url ?? `/files/get?fileId=${id}`;
            // 删除之前上传的附件
            if(this.applyItems[index]?.iconUrl){
              this.needServerDeleFiles.push({
                url: this.applyItems[index]?.iconUrl ?? '',
                id: this.applyItems[index]?.iconId ?? ''
              });
            }
            this.$set(this.applyItems[index], 'iconUrl', iconUrl)
            this.$set(this.applyItems[index], 'iconId', id)
            this.applyItems[index].icon = ''
          })
          .catch(err => {
            console.warn(err);
          })
          .finally(() => {
            this.loading = false;
          })
    },
    /** 改变值 */
    handleChange(value, index) {
      const selectDate = this.$refs.cascader[index]?.getCheckedNodes()?.[0]?.data || {};
      const { name = '', formOutBidId = '' } = selectDate;

      const applyItem = this.applyItems[index];
      applyItem.templateBizId = value[value.length - 1];
      applyItem.applicationName = name;
      applyItem.formOuterBizId = formOutBidId;
    },
    /** 设置颜色 */
    selectColor(color, index) {
      this.applyItems[index].color = color;
    },
    /** 设置icon */
    selectAppIcon(icon, index) {
      this.applyItems[index].icon = icon;

      // 删除之前上传的附件
      if(this.applyItems[index]?.iconUrl){
        this.needServerDeleFiles.push({
          url: this.applyItems[index]?.iconUrl ?? '',
          id: this.applyItems[index]?.iconId ?? ''
        });
      }

      this.applyItems[index].iconUrl = ''
      this.applyItems[index].iconId = ''
    },
    isSelected(color, apply) {
      return apply.icon == color;
    },
    /** 添加应用 */
    addApply() {
      this.applyItems.push({
        applicationName: '',
        formTemplateValue: [],
        templateBizId: '',
        formOuterBizId: '',
        color: Default_Color,
        icon: Default_Logo,
        cusstomerLink: '',
      });
      this.$emit('addPaasTemplate',this.applyItems)
    },
    /** 删除 */
    onDel(index) {
      this.applyItems.splice(index, 1);
    },
    /* 查询表单模板列表 */
    fetchFormTemplateList() {
      PassApi.getAllTemplateList()
        .then(res => {
          let { success, data = [] } = res || {};
          if (success) {
            data.unshift({name: this.$t('setting.enterprise.quickEntrance.customLink.title'), code: 'CustomLink'});
            this.formTemplateList = data;
            // 不存在的表单id置空
            this.applyItems.map(item => {
              if(!this.isIdExists(this.formTemplateList, item.templateBizId)) {
                item.templateBizId = ''
              }
            })
          }
        })
        .catch(err => console.log(err));
    },
    isIdExists(jsonData, id) {
      // 遍历JSON数据
      for (let i = 0; i < jsonData.length; i++) {
        const item = jsonData[i];
        
        // 检查当前项的code属性是否与给定的ID匹配
        if (item.code === id) {
          return true;
        }
        
        // 如果当前项有children属性，则递归调用isIdExists函数继续匹配
        if (item.children && item.children.length > 0) {
          if (this.isIdExists(item.children, id)) {
            return true;
          }
        }
      }
      
      // 如果没有找到匹配的ID，则返回false
      return false;
    }
  },
};
</script>
<style lang="scss" scoped>
.paas-apply-template {
  color: $text-color-primary;
  background: #fff;

  .paas-apply-item {
    background: #f2f2f2;
    margin: 10px 0;
    padding: 12px;

    .paas-apply-li {
      .el-input {
        margin-bottom: 10px;
      }
      .el-cascader {
        width: 100%;
        margin-bottom: 10px;
      }

      .apply-name {
        display: flex;
        justify-content: space-between;
        line-height: 22px;
        margin-bottom: 2px;

        p {
          margin-bottom: 0px;
        }

        .del {
          cursor: pointer;
        }
      }

      .apply-icon {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        cursor: pointer;
        width: 135px;
        .icon {
          width: 40px;
          height: 40px;
          border-radius: 12px;
          cursor: pointer;
          line-height: 40px;
          text-align: center;
          .iconfont {
            color: #fff;
            font-size: 18px;
          }
        }
        .apply-icon-img {
          width: 40px;
          height: 40px;
          border-radius: 12px;
          cursor: pointer;
          line-height: 40px;
          text-align: center;
        }

        span {
          margin-left: 8px;
          color: $text-color-secondary;
        }
      }
    }
  }

  .add-apply {
    margin-top: 10px;

    p {
      background: #f5f8fa;
      border: 1px solid #cbd6e2;
      // width: 377px;
      height: 32px;
      border-radius: 4px;
      line-height: 32px;
      text-align: center;
      font-size: 14px;
      color: $text-color-regular;
      cursor: pointer;
    }
  }
}

.select-app-icon-logo {
  .app-icon {
    display: flex;
  }

  .logo-color {
    display: inline-flex;
    width: 24px;
    height: 24px;
    border-radius: 12px;
    margin-right: 12px;
    justify-content: center;
    align-items: center;

    i {
      color: #fff;
    }
  }

  .app-logo {
    max-height: 274px;
    overflow: auto;
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
    padding: 14px 0 !important;
    margin: 0 !important;

    .app-logo-item {
      width: 50px;
      height: 50px;
      border-radius: 4px;
      border: 1px solid #d9d9d9;
      margin: 6px;
      display: flex;
      align-items: center;
      justify-content: center;

      i {
        font-size: 25px;
      }
    }
  }

  .custom-image {
    display: flex;
    align-items: center;
    margin-top: 12px;
    margin-left: 10px;
    font-size: 12px;
    color: rgba(0, 0, 0, 0.45);

    .el-upload {
      margin-right: 12px;

      div {
        width: 120px;
        height: 32px;
        border-radius: 3px;
        background: #ffffff;
        border: 1px solid rgba(0, 0, 0, 0.15);
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.65);

        span {
          margin-left: 10px;
        }
      }
    }

    .desc {
      margin-left: 8px;
    }
  }
}</style>
